﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using SharedCongkak;

namespace Congkak
{
    public class PickState: GameState
    {
        private AbstractHole selectedHole;

        public PickState(GameplayScreen gamePlay)
            : base(gamePlay)
        {
            level.OnHoleSelect += HoleSelected;
            level.AutoChooseHole();
        }

        public override void HandleInput(InputState input, PlayerIndex? ControllingPlayer)
        {
            PlayerIndex pressingPlayer;

            if (input.IsNewKeyPress(Keys.Down, ControllingPlayer, out pressingPlayer))
            {
                level.HightlightPrevHole();
            }
            else if (input.IsNewKeyPress(Keys.Up, ControllingPlayer, out pressingPlayer))
            {
                level.HightlightNextHole();
            }

            int mouseX, mouseY;
            InputState.MouseButton button;

            if (input.IsMouseMoved(out mouseX, out mouseY))
            {
                level.Hover(mouseX, mouseY);
            }
          
            if (input.IsMouseClicked(InputState.MouseButton.Middle, out mouseX, out mouseY))
            {
                gamePlay.ChangeGameState(new EditState(gamePlay));
            }


            if (input.IsMousePressed(out button, out mouseX, out mouseY))
            {
                AbstractHole hole = level.GetHole(new Point(mouseX, mouseY));
                if (hole != null)
                {
                    if (button == InputState.MouseButton.Left)
                    {
                        selectedHole = level.GetHole(new Point(mouseX, mouseY));
                        level.HighlightHole(selectedHole, null);
                    }
                }
            }


            if (input.IsMouseReleased(out button, out mouseX, out mouseY))
            {

                AbstractHole hole = level.GetHole(new Point(mouseX, mouseY));
                if (selectedHole != null && selectedHole == hole)
                {
                    level.Click(mouseX, mouseY);
                }
                selectedHole = null;
            }
            
        }

        public void HoleSelected(object hole, EventArgs eventArgs)
        {
            Hole selectedHole = hole as Hole;
            if (selectedHole == null)
                return;
            if (selectedHole.NoOfSeeds != 0 && selectedHole.IsHome)
                gamePlay.CollectFromHole(hole as Hole);
        }

        public override void Update(GameTime gameTime)
        {
            if (!level.IsValidMoves())
                gamePlay.ChangeGameState(new GameOverState(gamePlay));
        }


    }
}
